<template>
  <div class="coupon-page">
    <!-- 头部 -->
    <el-page-header title="刷新页面" @back="$router.go(0)" class="page-header">
      <template #content>
        <button class="page-title" @click="$router.push('/myCoupons')" >我的优惠券</button>
      </template>
    </el-page-header>

    <!-- 主体内容 -->
    <div class="coupon-container">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-wrapper">
        <el-icon class="loading-icon" :size="30"><Loading /></el-icon>
        <span>加载中...</span>
      </div>

      <!-- 空状态 -->
      <el-empty v-else-if="!loading && coupons.length === 0" description="暂无优惠券" />

      <!-- 优惠券列表 -->
      <div v-else class="coupon-list">
        <div
          v-for="coupon in coupons"
          :key="coupon.couponId"
          class="coupon-item"
          :class="{ 'expired': isExpired(coupon.couponEndTime), 'sold-out': coupon.couponCounts <= 0 }"
        >
          <div class="coupon-left">
            <div class="coupon-value">
              <span class="currency">¥</span>
              <span class="amount">{{ coupon.couponPrice }}</span>
            </div>
            <div class="coupon-condition">{{ coupon.couponRule }}</div>
          </div>
          
          <div class="coupon-right">
            <div class="coupon-name">通用优惠券</div>
            <div class="coupon-time">
              <el-icon><Timer /></el-icon>
              <span>有效期至: {{ formatDate(coupon.couponEndTime) }}</span>
            </div>
            <div class="coupon-count">
              <el-icon><Tickets /></el-icon>
              <span>剩余: {{ coupon.couponCounts }}张</span>
            </div>
            
            <el-button
              class="get-btn"
              type="warning"
              :disabled="isExpired(coupon.couponEndTime) || coupon.couponCounts <= 0"
              @click="grabCoupon(coupon.couponId)"
            >
              {{ getButtonText(coupon) }}
            </el-button>
          </div>

          <!-- 过期/售罄标签 -->
          <div v-if="isExpired(coupon.couponEndTime)" class="status-tag expired-tag">
            <el-tag type="info" effect="dark">已过期</el-tag>
          </div>
          <div v-else-if="coupon.couponCounts <= 0" class="status-tag sold-out-tag">
            <el-tag type="danger" effect="dark">已抢光</el-tag>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { Timer, Tickets, Loading } from '@element-plus/icons-vue'
import { couponsAPI } from '@/http'

// 接口类型定义
interface Coupon {
  couponId: number
  couponPrice: number
  couponStartTime: string
  couponEndTime: string
  couponCounts: number
  couponTpye: any
  couponRule: string
  yy: any
  couponStatus: any
}

// 状态管理
const coupons = ref<Coupon[]>([])
const loading = ref(true)

// 生命周期钩子
onMounted(() => {
  fetchCoupons()
})

// 获取优惠券列表
const fetchCoupons = async () => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  try {
    const res = await couponsAPI.getProductList()
    console.log('API响应:', res)
    
    // 处理不同响应结构
    coupons.value = Array.isArray(res) ? res : res.data || []
    
    if (coupons.value.length === 0) {
      ElMessage.warning('暂无可用优惠券')
    }
  } catch (error) {
    console.error('获取优惠券失败:', error)
    ElMessage.error('获取优惠券失败，请稍后重试')
  } finally {
    loading.value = false
    loadingInstance.close()
  }
}

// 领取优惠券
const grabCoupon = async (id: number) => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '领取中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  try {
    await couponsAPI.getCoupon(id)
    ElMessage.success('领取成功')
    // 刷新列表
    await fetchCoupons()
  } catch (error) {
    console.error('领取失败:', error)
    ElMessage.error('领取失败: ' + (error as Error).message || '未知错误')
  } finally {
    loadingInstance.close()
  }
}

// 辅助函数
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return `${date.getFullYear()}.${(date.getMonth() + 1).toString().padStart(2, '0')}.${date.getDate().toString().padStart(2, '0')}`
}

const isExpired = (endTime: string) => {
  return new Date(endTime) < new Date()
}

const getButtonText = (coupon: Coupon) => {
  if (isExpired(coupon.couponEndTime)) return '已过期'
  if (coupon.couponCounts <= 0) return '已抢光'
  return '立即领取'
}
</script>

<style scoped lang="scss">
.coupon-page {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding: 20px;
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 24px;
  
  .page-title {
    border: 0.5 solid #e6a23c;
    color: #e6a23c;
    font-size: 24px;
    margin: 0;
    font-weight: bold;
  }
}

.coupon-container {
  max-width: 800px;
  margin: 0 auto;
}

.loading-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  
  .loading-icon {
    margin-bottom: 10px;
    animation: rotate 2s linear infinite;
  }
  
  @keyframes rotate {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
  }
}

.coupon-list {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
}

.coupon-item {
  position: relative;
  display: flex;
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  
  &:hover:not(.expired):not(.sold-out) {
    transform: translateY(-5px);
    box-shadow: 0 6px 18px rgba(230, 162, 60, 0.2);
  }
  
  &.expired {
    opacity: 0.7;
    filter: grayscale(0.7);
  }
  
  &.sold-out {
    opacity: 0.8;
  }
}

.coupon-left {
  width: 140px;
  min-height: 160px;
  background: linear-gradient(135deg, #f0c78a, #e6a23c);
  color: white;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px 0;
}

.coupon-right {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.coupon-value {
  text-align: center;
  margin-bottom: 12px;
  
  .currency {
    font-size: 20px;
    vertical-align: top;
  }
  
  .amount {
    font-size: 36px;
    font-weight: bold;
    margin-left: 2px;
  }
}

.coupon-condition {
  font-size: 14px;
  text-align: center;
  padding: 0 10px;
}

.coupon-name {
  font-size: 18px;
  font-weight: bold;
  color: #e6a23c;
  margin-bottom: 12px;
}

.coupon-time,
.coupon-count {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  
  .el-icon {
    margin-right: 6px;
    font-size: 16px;
  }
}

.get-btn {
  margin-top: auto;
  align-self: flex-end;
  background: linear-gradient(135deg, #f0c78a, #e6a23c);
  border: none;
  color: white;
  font-weight: bold;
  
  &:hover {
    background: linear-gradient(135deg, #e6a23c, #f0c78a);
  }
  
  &.is-disabled {
    background: #bbb;
    cursor: not-allowed;
  }
}

.status-tag {
  position: absolute;
  top: 10px;
  right: 10px;
}

@media (max-width: 768px) {
  .coupon-item {
    flex-direction: column;
  }
  
  .coupon-left {
    width: 100%;
    min-height: auto;
    padding: 15px 0;
  }
  
  .coupon-right {
    padding: 15px;
  }
  
  .amount {
    font-size: 28px !important;
  }
}
</style>